package handler

import (
	"fmt"
	"go-devops/common"
	"go-devops/domain/dto"
	"log"
	"path/filepath"
	"strings"
)

type MavenTaskHandler struct {
	CommonTaskHandler
}

func NewMavenTaskHandler() *MavenTaskHandler {
	return &MavenTaskHandler{
		CommonTaskHandler: CommonTaskHandler{},
	}
}

type MavenData struct {
	Command     string `json:"command"`
	PomPath     string `json:"pomPath"`
	DockerImage string `json:"dockerImage"`
	WorkDir     string `json:"workDir"`
}

func getMavenData(context *dto.NodeContext) MavenData {
	data := context.TaskData.Data
	jsonString := common.JsonString(data)
	var mavenData MavenData
	common.ParseJson(jsonString, &mavenData)
	return mavenData
}

func (c MavenTaskHandler) Stop(context *dto.NodeContext) error {
	context.StopFlag = true
	dockerId := context.DockerId
	if len(dockerId) <= 0 {
		return nil
	}

	command := fmt.Sprintf("docker stop %s", dockerId)
	err := ExecCmd(context, command, context.Workspace, true)
	return err
}

func (c MavenTaskHandler) HandleNode(nodeContext *dto.NodeContext) error {
	return c.Handle(nodeContext, func() error {
		workspace := nodeContext.Workspace
		log.Println("工作空间：" + workspace)
		sendMsg(nodeContext, true, fmt.Sprintf("工作空间：%s", workspace))

		data := getMavenData(nodeContext)
		log.Printf("MavenTaskHandler data:%+v\n", data)
		dataJson := common.JsonString(data)
		sendMsg(nodeContext, true, fmt.Sprintf("taskData:%s", dataJson))

		// 检查docker环境
		dir := workspace
		if len(data.WorkDir) > 0 && strings.HasPrefix(data.WorkDir, "/") {
			dir = dir + data.WorkDir
		} else {
			dir = filepath.Join(dir, data.WorkDir)
		}

		pomPath := dir
		if len(data.PomPath) > 0 {
			pomPath = filepath.Join(pomPath, data.PomPath)
		}

		node := common.Config.Node
		dockerPath := filepath.Join(node.DockerPath, nodeContext.TaskId)
		dockerImage := data.DockerImage
		command := fmt.Sprintf("docker run -i --name %s --rm -v %s:/home/repo -v %s:%s -w %s %s %s",
			nodeContext.DockerId, node.MavenRepo, pomPath, dockerPath, dockerPath, dockerImage, data.Command)
		err := ExecCmd(nodeContext, command, dir, true)
		if err != nil {
			return err
		}
		return nil
	})
}
